import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '@/pages/Admin'
// import NotFound from '@pages/NotFound'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/admin/dashBoard'
  },
  {
    path: '/admin',
    name: 'admin',
    admin: true,
    component: Admin,
    meta: {
      isNav: false,
      roles: ['admin', 'edit', 'superAdmin']
    },
    children: [
      // 仪表盘
      {
        path: '/admin/dashBoard',
        name: '仪表盘',
        icon: 'el-icon-pie-chart',
        component: () => import('@/pages/DashBoard'),
        meta: {
          isNav: true,
          roles: ['admin', 'edit', 'superAdmin']
        }
      },
      // 文章列表
      {
        path: '/admin/artList',
        name: '文章列表',
        icon: 'el-icon-menu',
        component: () => import('@/pages/ArtList'),
        meta: {
          isNav: true,
          roles: ['admin', 'edit', 'superAdmin']
        }
      },
      {
        path: '/admin/message',
        name: '消息中心',
        icon: 'el-icon-chat-dot-square',
        component: () => import('@/pages/Message'),
        meta: {
          isNav: true,
          roles: ['admin', 'edit', 'superAdmin']
        }
      },
      // 设置
      {
        path: '/admin/settings',
        name: '设置',
        icon: 'el-icon-s-tools',
        component: () => import('@/pages/Settings'),
        meta: {
          isNav: true,
          roles: ['admin', 'edit', 'superAdmin']
        }
      },
      // 文章添加
      {
        path: '/admin/artAdd',
        name: 'ArtAdd',
        component: () => import('@/pages/ArtAdd'),
        meta: {
          isNav: false,
          roles: ['edit', 'superAdmin']
        }
      },
      // 文章编辑
      {
        path: '/admin/artEdit/:id',
        name: 'artEdit',
        component: () => import('@/pages/ArtEdit'),
        meta: {
          isNav: false,
          roles: ['edit', 'superAdmin']
        }
      },
      // 权限
      {
        path: '/admin/permission',
        name: 'permission',
        component: () => import('@/pages/Permission'),
        meta: {
          isNav: false,
          roles: ['admin', 'edit', 'superAdmin']
        }
      }
    ]
  },
  // 登录页
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login'),
    meta: {}
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 判断是不是去登录
  if (to.fullPath === '/login') {
    // 是就放行
    next()
  } else {
    // 如果不是在判断有没有登录
    const accessToken = localStorage.getItem('accessToken')
    if (accessToken) {
      // 判断是否需要权限
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const isRole = to.meta.roles.some(role => userInfo.role === role)
      if (isRole) {
        next()
      } else {
        next('/admin/permission')
      }
    } else {
      // 没有登录就跳转到登录页
      next({ name: 'Login', params: { path: to.fullPath } })
    }
  }
})
export default router
